<template>
  <div class="app-container">
    <el-row v-if="optType != 'finish'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="optType != 'view' && optType != 'confirm'" icon="el-icon-plus" plain size="mini" type="primary"
                   @click="handleAdd">新增
        </el-button>
        <el-button v-if="this.viewDrawing" icon="el-icon-view" plain size="mini" type="primary" @click="handleView">
          图纸查看
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="protaskList" border @selection-change="handleSelectionChange">
      <el-table-column :show-overflow-tooltip="true" align="center" label="任务编号" prop="rrTaskCode" width="120px"/>
      <el-table-column :show-overflow-tooltip="true" align="center" label="任务名称" prop="rrTaskName" width="120px"/>
      <el-table-column align="center" label="排产数量" prop="quantity">
        <template slot-scope="scope">
          <el-tag type="danger">{{ scope.row.quantity }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已生产数量" prop="quantityProduced" width="100px">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.quantityProduced }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" align="center" label="工作站编号" prop="workstationCode"
                       width="150px"/>
      <el-table-column :show-overflow-tooltip="true" align="center" label="工作站名称" prop="workstationName"
                       width="150px"/>
      <el-table-column align="center" label="计划开工时间" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d} {h}") }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="生产时长" prop="duration"/>
      <el-table-column align="center" label="计划完工时间" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d} {h}") }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="显示颜色" prop="colorCode">
        <template slot-scope="scope">
          <el-color-picker v-model="scope.row.colorCode" disabled></el-color-picker>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="120px">
        <template slot-scope="scope">
          <el-button
            v-if="optType != 'view' && optType != 'finish' && optType != 'confirm'&& scope.row.status == 'PENDUING'"
            v-hasPermi="['mes:pro:protask:edit']" icon="el-icon-edit" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button
            v-if="optType != 'view' && optType != 'finish' && optType != 'confirm' && scope.row.status == 'PENDUING'"
            v-hasPermi="['mes:pro:protask:remove']" icon="el-icon-delete" size="mini" type="text"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改返修任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="1080px">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作站" prop="workstationName">
              <el-input v-model="form.workstationName" placeholder="请选择工作站">
                <el-button slot="append" icon="el-icon-search" @click="handleWorkstationSelect"></el-button>
              </el-input>
            </el-form-item>
            <WorkstationSelect ref="wsSelect" :processId="processId"
                               @onSelected="onWorkstationSelected"></WorkstationSelect>
          </el-col>
          <el-col :span="5">
            <el-form-item label="甘特图显示颜色" prop="colorCode">
              <el-color-picker v-model="form.colorCode"></el-color-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-input v-model="form.colorCode" maxlength="7" placeholder="请输入颜色编码在左侧选择颜色"/>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="排产数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="1" placeholder="请输入排产数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作人" prop="attr1">
              <el-input v-model="form.attr1" placeholder="请选择操作人">
                <el-button slot="append" icon="el-icon-search" @click="handleUserSelect"></el-button>
              </el-input>
            </el-form-item>
            <UserMultiSelect ref="userSelect" @onSelected="onUserSelected"></UserMultiSelect>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车间名称" prop="attr2">
              <el-input v-model="form.attr2" disabled placeholder="请选择车间"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" clearable placeholder="请选择开始生产时间" type="datetime"
                              value-format="yyyy-MM-dd HH" @change="calculateEndTime"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产时长" prop="duration">
              <el-input-number v-model="form.duration" :min="1" :precision="0" :step="1" placeholder="请输入生产时长"
                               @change="calculateEndTime"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成时间" prop="endTime">
              <el-date-picker v-model="form.endTime" clearable disabled type="datetime"
                              value-format="yyyy-MM-dd HH"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图纸搜索页面 -->
    <el-dialog :title="title" :visible.sync="viewOpen" append-to-body width="1100px">
      <PdfView :url="this.url" :workorderId="this.rrWorkorderId" :processId="this.processId"></PdfView>
    </el-dialog>
  </div>
</template>

<script>
import {listTask, getTask, delTask, addTask, updateTask} from '@/api/mes/rr/rrtask';
import WorkstationSelect from '@/components/workstationSelect/simpletableSingle.vue';
import UserMultiSelect from '@/components/userSelect/multi.vue';
import PdfView from '@/components/pdfView/view.vue'

export default {
  name: "rrTask",
  components: {PdfView, UserMultiSelect, WorkstationSelect},
  data() {
    return {
      url: '/rr/retrunrepairline/getList',
      viewDrawing: true,
      viewOpen: false, // 遮罩层
      loading: true, // 选中数组
      ids: [], // 非单个禁用
      single: true, // 非多个禁用
      multiple: true, // 显示搜索条件
      showSearch: true, // 总条数
      total: 0, // 返修任务表格数据
      protaskList: [], // 弹出层标题
      title: "", // 是否显示弹出层
      open: false, // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rrWorkorderId: this.rrWorkorderId,
        processId: this.processId,
      }, // 表单参数
      form: {}, // 表单校验
      rules: {
        workstationName: [{required: true, message: "工作站不能为空", trigger: "blur"},],
        quantity: [{required: true, message: "排产数量不能为空", trigger: "blur"},],
        startTime: [{required: true, message: "请选择开始生产日期", trigger: "blur"},],
        duration: [{required: true, message: "请输入估算的生产用时", trigger: "blur"},],
        attr1: [{required: true, message: "请选择操作人", trigger: "blur"}],
      },
    };
  },
  props: {
    rrWorkorderId: null,
    colorCode: null,
    processId: null,
    optType: null,
    quantity: null,
  },
  computed: {
    rrTask() {
      const {processId} = this;
      return {
        processId,
      };
    },
  },

  watch: {
    // 监听 planning 值的变化
    rrTask: {
      handler(newValue, oldValue) {
        this.queryParams.processId = newValue.processId;
        this.getList();
      }, deep: true,
    },
  },

  created() {
    this.getList();
  },
  methods: {
    /** 查询返修任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then((response) => {
        this.protaskList = response.rows;
        if (this.protaskList && this.protaskList.length > 0) {
          this.viewDrawing = !this.protaskList.every((item) => item.status === "FINISHED");
        }
        this.total = response.total;
        this.loading = false;
      });
    }, //计算结束时间
    calculateEndTime() {
      if (this.form.startTime != null && this.form.duration != null) {
        let parts = this.form.startTime.split(" ");
        let startDate = new Date(parts[0]);
        startDate = startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate() + " " + parts[1].split(":")[0] + ":" + "00" + ":" + "00";
        this.form.startTime = startDate;
        startDate = Date.parse(new Date(startDate)) / 1000;
        startDate += 3600 * 1 * this.form.duration; //这里以1小时为一个单位
        let endDate = new Date(parseInt(startDate) * 1000);
        this.form.endTime = endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate() + " " + endDate.getHours() + ":" + endDate.getMinutes() + ":" + endDate.getSeconds();
      }
    }, // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    }, // 表单重置
    reset() {
      this.form = {
        rrTaskId: null,
        rrTaskCode: null,
        rrTaskName: null,
        rrWorkorderId: this.rrWorkorderId,
        rrWorkorderCode: null,
        rrWorkorderName: null,
        workstationId: null,
        workstationCode: null,
        workstationName: null,
        processId: this.processId,
        processCode: null,
        processName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        clientNick: null,
        startTime: null,
        duration: null,
        endTime: null,
        colorCode: this.colorCode,
        requestDate: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    }, /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    }, /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    }, // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.rrTaskId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    }, /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.quantity = this.quantity;
      this.open = true;
      this.title = "添加返修任务";
    }, /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const rrTaskId = row.rrTaskId || this.ids;
      getTask(rrTaskId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改返修任务";
      });
    }, /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.rrTaskId != null) {
            updateTask(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    }, /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.rrTaskId || this.ids;
      this.$modal
        .confirm('是否确认删除返修任务编号为"' + row.rrTaskCode + '"的数据项？')
        .then(function () {
          return delTask(taskIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
    handleWorkstationSelect() {
      this.$refs.wsSelect.showFlag = true;
    },
    onWorkstationSelected(row) {
      if (row != undefined && row != null) {
        this.form.workstationId = row.workstationId;
        this.form.workstationCode = row.workstationCode;
        this.form.workstationName = row.workstationName;
        this.form.attr2 = row.workshopName;
        this.form.attr4 = row.workshopId;
      }
    }, //点击人员选择按钮
    handleUserSelect() {
      this.$refs.userSelect.showFlag = true;
    }, //人员选择返回
    onUserSelected(row) {
      if (row != undefined && row != null) {
        this.form.attr1 = row.map((item) => item.nickName).join(",");
        this.form.attr3 = row.map((item) => item.userId).join(",");
      }
    },
    handleView() {
      this.title = "图纸";
      this.viewOpen = true;
    },
  },
};
</script>
